package com.share.domain;

import com.share.dbutils.QueryFactory;
import com.share.entity.Blog;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by leep on 2015-12-26.
 */
public class BlogDomainImpl implements BlogDomain {
	public List<Blog> getBlogs(int page) {
		QueryRunner queryRunner = QueryFactory.getQueryRunner();
		String sql = "select * from blog order by createTime desc limit ?,?";
		ResultSetHandler handler = new BeanListHandler(Blog.class);
		try {
			List<Blog> blogs = (List<Blog>) queryRunner.query(sql, handler, page * 20, 20);
			return blogs;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public boolean save(Blog blog) {
		QueryRunner queryRunner = QueryFactory.getQueryRunner();
		String sql = "insert into blog (content,createTime) values(?,?)";
		ResultSetHandler handler = new BeanHandler(Blog.class);
		try {
			queryRunner.insert(sql, handler, blog.getContent(), blog.getCreateTime());
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	public Blog getBlogById(int blogId) {
		QueryRunner queryRunner = QueryFactory.getQueryRunner();
		String sql = "select * from blog where id=?";
		ResultSetHandler handler = new BeanHandler(Blog.class);
		try {
			return (Blog) queryRunner.query(sql, handler, blogId);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public boolean update(Blog blog) {
		QueryRunner queryRunner = QueryFactory.getQueryRunner();
		String sql = "update blog set commentNum=? where id=?";
		try {
			queryRunner.update(sql, blog.getCommentNum(), blog.getId());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
